<?php

/*
 * Created on 2012-10-10
 * BY S67
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'nl_config.class.php';
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'nl_dc.class.php';
include_once NPDIR . 'np_string.php';
include_once NPDIR . 'np_db.class.php';
include_once NPDIR . 'np_db_factory.php';
include_once NPDIR . 'np_kv_cache_factory.php';
include_once NPDIR . 'np_kv_cache.class.php';
include_once NPDIR . 'np_php_base.php';
include_once NPDIR . 'np_time.php';
include_once NPDIR . 'np_log.class.php';
include_once NPDIR . 'np_authcode.php';
include_once NPDIR . 'np_redis.class.php';
include_once NPDIR . 'np_redis_null.class.php';
if (file_exists(NPDIR . 'np_db_check.class.php'))
{
	include_once NPDIR . 'np_db_check.class.php';
}
if(file_exists(NPDIR . 'np_sql_builder.class.php'))
{
    include_once NPDIR . 'np_sql_builder.class.php';
}
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'nl_log_v2.func.php';
// include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'config/nl_config.php';
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'nl_constant.php';
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'nl_sub_platform_common.func.php';
/**
 * 根据当前配置获取底层数据操作模块
 * @param Array(
 * 			'db_policy'=>db配置，标识读或写，NL_DB_WRITE | NL_DB_READ
 * 			'cache_policy'=>cache配置,标识cache策略 NP_KV_CACHE_TYPE_NULL | NP_KV_CACHE_TYPE_MEMCACHE | NP_KV_CACHE_TYPE_MEMCACHED
 * 			)
 * @param Array(
 * 			'db_log'=>  数据库操作调试参数 NP_DB_LOG_NULL | NP_DB_LOG_ERROR | NP_DB_LOG_ALL
 * 			'cache_type'=>  cache存储类型 NP_KV_CACHE_MAP_ALL | NP_KV_CACHE_MAP_HASH
 * 			)
 * @return nl_dc 数据底层操作模块
 */
function nl_get_dc($config, $params = NULL) {
// 	if(is_object(nl_dc::$obj_dc) && nl_dc::$obj_dc != null)
// 	{
// 		$db_obj = nl_dc::$obj_dc;
// 		if($db_obj->is_db_open() !== FALSE)
// 		{
// 			return $db_obj;
// 		}
// 		nl_dc::$obj_dc = null;
// 	}
	$db_obj = new nl_dc($config, $params);
 	return $db_obj;
}

/*
 * ********************************************************************************
 * 	DB模块相关方法
 * 	nl_get_db
 * 	nl_get_db_config
 * 	nl_get_db_w_config_list
 * 	nl_get_db_r_config_list
 * 	nl_query_by_db
 * 	nl_execute_by_db
 * ******************************************************************************* */

/**
 * 根据当前配置获取DB模块
 * @param String 数据库类型读或写 NL_DB_WRITE | NL_DB_READ
 * @param Array(
 * 			'db_log'=> 数据库操作调试参数 NP_DB_LOG_NULL | NP_DB_LOG_ERROR | NP_DB_LOG_ALL
 * 			)
 * 			数据库底层行为控制参数组
 * @return db db数据库操作模块
 */
function nl_get_db($db_policy, $params = null)
{

    $db_type = '';
    if(isset($params['db_type']))
    {
        $db_type = $params['db_type'];
    }
    else
    {
        $db_type = NP_DB_TYPE_MYSQL;
    }
 $c = nl_get_db_config($db_policy);
 
    if(is_array($params))
    {
        if(array_key_exists('db_log', $params))
        {
            $c['db_log'] = $params['db_log'];  //	重构数据模块调试参数
        }
        if(array_key_exists('db_type', $params))
        {
            $c['db_type'] = $params['db_type'];  //	重构数据模块调试参数
        }

        if(defined('g_db_hash_table_rules'))
        {
            $g_db_hash_table_rules = constant('g_db_hash_table_rules');
            $c['db_hash_table_rules'] = explode(";", $g_db_hash_table_rules);
        }

        if(defined('g_db_hash_table_modes'))
        {
            $g_db_hash_table_mode = constant('g_db_hash_table_modes');
            $c['db_hash_table_modes'] = explode(";", $g_db_hash_table_mode);
        }

        if(array_key_exists('db_hash_table_modes', $params))
        {
            $c['db_hash_table_modes'] = $params['db_hash_table_modes'];  //	重构数据模块调试参数
        }
    }


    $db = np_db_factory_create($c);

    return $db;
}

/**
 * 根据读写类型获取数据库当前采用配置
 * @param String 数据库类型读或写 NL_DB_WRITE | NL_DB_READ
 * @return Array 当前数据库采用配置
 */
function nl_get_db_config($db_policy) {
 $w_configs = nl_get_db_w_config_list();
 $r_configs = nl_get_db_r_config_list();

 $configs = nl_get_active_db_config_by_ini($w_configs, $r_configs);

 $w_active_configs = $configs['write'];
 $r_active_configs = $configs['read'];

 if ($db_policy === NL_DB_WRITE) {
  $c = _get_w_db_config($w_active_configs, $r_active_configs);
 } elseif ($db_policy === NL_DB_READ) {
  $c = _get_r_db_config($w_active_configs, $r_active_configs);
 }

 if ($c === NULL) {
  if ($db_policy === NL_DB_WRITE) {
	$c = _get_w_db_config($w_configs, $r_configs);
  } elseif ($db_policy === NL_DB_READ) {
	$c = _get_r_db_config($w_configs, $r_configs);
  }
 }

//	var_dump($c);die;
 return $c;
}

function _get_r_db_config($w_configs, $r_configs) {
 switch (g_db_mode) {
  case 0:
	$c = _get_w_db_config($w_configs, $r_configs);
	break;
  case 1:
	if (count($r_configs) > 0) {
	 //		从DB配置组中获取DB写模块配置，当前为默认选择第一个。
	 $c = $r_configs[0];
	} else {
	 $c = _get_w_db_config($w_configs, $r_configs);
	}

	break;
  case 2:
	$c = _get_w_db_config($w_configs, $r_configs);
	if ($c === NULL) {
	 if (count($r_configs) > 0) {
	  $c = $r_configs[0];
	 } else {
	  $c = NULL;
	 }
	}
	break;
  case 30:
	if (count($r_configs) > 0) {
	 $c = _get_random_db_config($r_configs);
	} else {
	 $c = NULL;
	}
	break;

  case 31:
	if (count($r_configs) > 0) {
	 $c = $r_configs[0];
	} else {
	 $c = NULL;
	}
	break;
 }

 if (is_array($c))
  $c['mode'] = 'READ';

 return $c;
}

//随机选择configs组中任一config
function _get_random_db_config($configs) {
 $rand = rand(0, count($configs) - 1);
 return $configs[$rand];
}

function _get_w_db_config($w_configs, $r_configs) {
 $c = NULL;
 switch (g_db_mode) {
  case 0:
	if (count($w_configs) > 0) {
	 //		从DB配置组中获取DB写模块配置，当前为默认选择第一个。
	 $c = $w_configs[0];
	 $c['mode'] = 'WRITE';
	}
	break;
  case 1:
	if (count($w_configs) > 0) {
	 //		从DB配置组中获取DB写模块配置，当前为默认选择第一个。
	 $c = $w_configs[0];
	 $c['mode'] = 'WRITE';
	}
	break;
  case 2:
	if (count($w_configs) > 0) {
	 //		从DB配置组中获取DB写模块配置，当前为默认选择第一个。
	 $c = $w_configs[0];
	 $c['mode'] = 'WRITE';
	} else {
	 if (count($r_configs) > 0) {
	  $c = $r_configs[0];
	  $c['mode'] = 'READ';
	 }
	}
	break;
  case 30:
	if (count($r_configs) > 0) {
	 $c = _get_random_db_config($r_configs);
	 $c['mode'] = 'READ';
	} else {
	 $c = NULL;
	}
	break;

  case 31:
	if (count($r_configs) > 0) {
	 $c = $r_configs[0];
	 $c['mode'] = 'READ';
	} else {
	 $c = NULL;
	}
	break;
 }

 return $c;
}

/**
 * 获取当前能用的配置
 * @param Array 配置组
 * @return Array 当前数据库采用配置
 */
function nl_get_active_db_config_by_ini($wconfigs, $rconfigs) {
 $lines = array();
 $db_ini = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nn_cms_config' . DIRECTORY_SEPARATOR . 'global_db_ini';
 if (file_exists($db_ini)) {
  $handle = @fopen($db_ini, "r");
  if ($handle) {
	while (!feof($handle)) {
	 $lines[] = fgets($handle, 4096);
	}
	fclose($handle);
  }
 } else {
  return array('write' => $wconfigs, 'read' => $rconfigs);
 }
//	var_dump($lines);die;
 $active_w_indexse = null;
 $active_r_indexse = null;
 if (empty($lines))
  return array('write' => $wconfigs, 'read' => $rconfigs);

 $lines[0] = trim($lines[0]);
 $lines[1] = trim($lines[1]);
 $lines[2] = trim($lines[2]);


 if (strtotime(date('YmdHis')) - strtotime($lines[0]) > 10) {
  return array('write' => $wconfigs, 'read' => $rconfigs);
 }

 $active_w_indexse = ',' . $lines[1] . ',';
 $active_r_indexse = ',' . $lines[2] . ',';


 $active_wconfigs = array();
 foreach ($wconfigs as $w_key => $w_value) {
  if (strpos($active_w_indexse, ',' . $w_key . ',') !== FALSE) {
	array_push($active_wconfigs, $w_value);
  }
 }

 $active_rconfigs = array();
 foreach ($rconfigs as $r_key => $r_value) {
  if (strpos($active_r_indexse, ',' . $r_key . ',') !== FALSE) {
	array_push($active_rconfigs, $r_value);
  }
 }


 return array('write' => $active_wconfigs, 'read' => $active_rconfigs);
}

/**
 * 获取当前写类型数据库配置列表
 * @return Array 数据库配置组
 */
function nl_get_db_w_config_list() {
 $configs = array();
 for ($i = 1; $i <= 32; $i++) {
  if ($i === 1) {
	$c = np_db_build_config(
			  g_db_host, g_db_username, g_db_password, g_db_name, NP_DB_TYPE_MYSQL, NP_DB_LOG_NULL
	);
	if (isset($c)) {
	 array_push($configs, $c);
	}
  } elseif (defined('g_db_host' . $i)) {
	$c = np_db_build_config(
			  constant('g_db_host' . $i), constant('g_db_username' . $i), constant('g_db_password' . $i), constant('g_db_name' . $i), NP_DB_TYPE_MYSQL, NP_DB_LOG_NULL
	);
	if (isset($c)) {
	 array_push($configs, $c);
	}
  }
 }
 return $configs;
}

/**
 * 获取当前读类型数据库配置列表
 * @return Array 数据库配置组
 */
function nl_get_db_r_config_list() {
 $configs = array();
 for ($i = 1; $i <= 32; $i++) {
  if (defined('g_db_r_host' . $i)) {
	$c = np_db_build_config(
			  constant('g_db_r_host' . $i), constant('g_db_r_username' . $i), constant('g_db_r_password' . $i), constant('g_db_r_name' . $i), NP_DB_TYPE_MYSQL, NP_DB_LOG_NULL
	);
	if (isset($c)) {
	 array_push($configs, $c);
	}
  }
 }
 return $configs;
}

/**
 * 执行SQL查询
 * @param String SQL查询语句
 * @param db db数据库操作模块
 * @return *
 * 			FALSE为执行失败，
 * 			TRUE为执行成功，但数据为空，
 * 			Array为数据查询结果
 */
function nl_query_by_db($sql, $db) {
 if ($db == NULL) {
  nl_dc::throw_debug($sql, " db is null", 1);
  return FALSE;
 }
 // 如果是日志库，则直接返回TRUE  BY S67
 if ($db===-1){
 	return TRUE;
 }


 if (!$db->query($sql)) {
  nl_dc::throw_debug($sql, $db->last_error_desc(), $db->last_error_no());
//                nl_log('db')->write($sql . "\n" . $db->last_error_desc());
  return FALSE;
 }


 $q = $db->get_query_result(TRUE);
 if ($q === FALSE) {
  nl_dc::throw_debug($sql, $db->last_error_desc(), $db->last_error_no());
//                nl_log('db')->write($db->last_error_desc());
  return FALSE;
 }


 if (count($q) == 0) {
  nl_dc::throw_debug($sql, "query is empty");
  return TRUE;
 }

 nl_dc::throw_debug($sql, " query OK");
 return $q;
}

/**
 * 执行SQL增删改操作
 * @param String SQL语句
 * @param db db数据库操作模块
 * @return *
 * 			FALSE为执行失败，
 * 			TRUE为执行成功，
 */
function nl_execute_by_db($sql, $db) {
 if ($db == NULL) {
  nl_dc::throw_debug($sql, " db is null", 1);
//                nl_write_error('db is null');
  return FALSE;
 }
 
// 如果是日志库，则直接返回TRUE  BY S67
 if ($db===-1){
 	return TRUE;
 }

 $result = $db->execute($sql);
 if ($result == false) {
  nl_dc::throw_debug($sql, $db->last_error_desc(), $db->last_error_no());
  nl_write_error($sql . "\n" . $db->last_error_no() . "\n" . $db->last_error_desc());
  return FALSE;
 }
 nl_dc::throw_debug($sql, " execute OK");
 return $result;
}

/*
 * ********************************************************************************
 * 	CACHE模块相关方法
 * 	nl_get_cache
 * ******************************************************************************* */

/**
 * 获取cache操作模块
 * @param String cache类型 NP_KV_CACHE_TYPE_NULL | NP_KV_CACHE_TYPE_MEMCACHE | NP_KV_CACHE_TYPE_MEMCACHED
 * @param Array(
 * 			'cache_type'=> cache存储类型 NP_KV_CACHE_MAP_ALL | NP_KV_CACHE_MAP_HASH
 * 			)
 * 			cache层行为控制参数组
 * @return cache cache操作模块,NULL为无MEMCACH配置或MEMCACHE链接失败
 */
function nl_get_cache($cache_policy = NULL, $params = NULL) {

 if (!defined('g_memcache_server')) {

  return np_kv_cache_factory_create(
			 np_kv_cache_build_config(
						NP_KV_CACHE_TYPE_NULL, NP_KV_CACHE_MAP_ALL, array()
  )); //未定义memcache地址，则返回
 }

 if (g_memcache_server == '') {
  return np_kv_cache_factory_create(
			 np_kv_cache_build_config(
						NP_KV_CACHE_TYPE_NULL, NP_KV_CACHE_MAP_ALL, array()
  ));
 }

 $servers = explode(';', rtrim(g_memcache_server, ';'));

 if (empty($cache_policy) && $cache_policy !== NP_KV_CACHE_TYPE_NULL) {
  $cache_policy = NP_KV_CACHE_TYPE_MEMCACHE;  //未传入CACHE类型时，默认为 NP_KV_CACHE_TYPE_MEMCACHE
 }

 if (empty($params)) {
  $cache_type = NP_KV_CACHE_MAP_ALL;  //未传入存储类型时，默认为 NP_KV_CACHE_MAP_ALL
 } else {
  if (!array_key_exists('cache_type', $params)) {
	$cache_type = NP_KV_CACHE_MAP_ALL; //未传入存储类型时，默认为 NP_KV_CACHE_MAP_ALL
  } else {
	$cache_type = $params['cache_type'];
  }
 }



 $c = np_kv_cache_build_config(
			$cache_policy, $cache_type, $servers
 );

 $cache = np_kv_cache_factory_create($c);

 return $cache;
}

function nl_log($logic_model_name = '') {
 $log = new np_log_class();
 $log_path = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'nn_logic' . DIRECTORY_SEPARATOR . $logic_model_name;
 $log->set_path($log_path);
 return $log;
}

function nl_write_error($str) {
 $log = new np_log_class();
 $log_path = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . 'error';
 $log->set_path($log_path);
 $log->write($str);
}

function nl_db_query_and_or($param, $field) {
 $sql_link = ' and ';
 $param_values = explode('#', $param);
 if (count($param_values) == 0) {
  $sql_link = ' or ';
  $param_values = explode('|', $param);
 }

 $command_str = '';
 foreach ($param_values as $param_value) {
  $command_str.=$field . '=\'' . $param_value . '\' ' . $sql_link;
 }
 $command_str = rtrim($command_str, $sql_link);

 return $command_str;
}

function nl_db_insert($db, $table, $data) {
 $field_str = '';
 $value_str = '';
 foreach ($data as $k => $v) {
  if (strpos($k, 'nns_') === FALSE)
	$k = 'nns_' . $k;
  $field_str .= $k . ',';
  if(strlen($v)<1)
  {
      $value_str .= "'',";
  }
  else
  {
     $value_str .= "'$v',";
  }
 }
 $field_str = rtrim($field_str, ',');
 $value_str = rtrim($value_str, ',');
 $sql = "insert into $table ($field_str) values($value_str)";
 return nl_execute_by_db($sql, $db);
}

function nl_db_update($db, $table, $set, $where = null) {
 $set_str = '';
 if (is_string($set)) {
  $set_str = $set;
 } else if (is_array($set)) {
  foreach ($set as $k => $v) {
	if (strpos($k, 'nns_') === FALSE)
	 $k = 'nns_' . $k;
	$set_str .= "$k='$v',";
  }
  $set_str = rtrim($set_str, ',');
 }
 $wh = array();
 if (is_array($where)) {
  foreach ($where as $k => $v) {
	if (strpos($k, 'nns_') === FALSE)
	 $k = 'nns_' . $k;
	$wh[] = "$k='$v'";
  }
  !empty($wh) && $where = implode(' and ', $wh);
 }
 if (is_string($where) && $where)
  $where = "where $where";
 $sql = "update $table set $set_str  $where";
 return nl_execute_by_db($sql, $db);
}

function nl_db_in($ids, $filed = null) {

 $in_str = '';
 if (is_string($ids)) {
  $ids = explode(',', $ids);
 }
 $in_str = " in('" . implode("','", $ids) . "')";

 if ($filed)
  $in_str = $filed . $in_str;
 return $in_str;
}

function nl_db_get_all($sql, $db) {
 if ($db == NULL)
  return FALSE;
 
 if (!$db->query($sql)) {
	  nl_log('db')->write($sql . "\n" . $db->last_error_desc());
	  return FALSE;
 }


 $q = $db->get_query_result(TRUE);
 if ($q === FALSE)
  return FALSE;

 return $q;
}

function nl_db_get_col($sql, $db) {
 $result = nl_db_get_one($sql, $db);
 if ($result === false)
  return false;
 if (is_array($result) && !empty($result)) {
  $v = array_values($result);
  return $v[0];
 } else {
  return null;
 }
}

function nl_db_get_one($sql, $db) {
 $result = nl_query_by_db($sql, $db);
 if ($result === false)
  return false;
 return !empty($result) ? $result[0] : null;
}

/**
 * 自动加载logic层的类文件
 */
function nl_logic_autoload($classname) {
 $file_name = str_replace('nl_', '', $classname);

 $module_name = 'common';
 $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $module_name . DIRECTORY_SEPARATOR . $file_name . '.class.php';

 if (file_exists($file)) {
  include_once $file;
  return true;
 }

 $str_arr = explode('_', $file_name);
 //var_dump($str_arr);exit;
 $count = count($str_arr);
 $module_name = '';
 for ($i = 0; $i < $count; $i++) {
  $module_name .= '_' . $str_arr[$i];

  $module_name = ltrim($module_name, '_');

  $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $module_name . DIRECTORY_SEPARATOR . $file_name . '.class.php';

  if (file_exists($file)) {
	include_once $file;
	return true;
  }
 }

 return false;
}

spl_autoload_register('nl_logic_autoload');

/**
 * 按缓存key前缀删除缓存数据
 */
function nl_delete_cache_by_prefix($cache, $key_prefix) {
 $cache_keys = $cache->get_cache_keys();
 foreach ($cache_keys as $key) {
  if (false !== strpos($key, $key_prefix)) {
	$cache->delete($key);
  }
 }
}

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL) {
 $codetype = 'UTF-8';
 $do_dump_indent = "<span style='color:#666666;'>|</span> &nbsp;&nbsp; ";
 $reference = $reference . $var_name;
 $keyvar = 'the_do_dump_recursion_protection_scheme';
 $keyname = 'referenced_object_name';

 // So this is always visible and always left justified and readable
 echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";

 if (is_array($var) && isset($var[$keyvar])) {
  $real_var = &$var[$keyvar];
  $real_name = &$var[$keyname];
  $type = ucfirst(gettype($real_var));
  echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
 } else {
  $var = array($keyvar => $var, $keyname => $reference);
  $avar = &$var[$keyvar];

  $type = ucfirst(gettype($avar));
  if ($type == "String")
	$type_color = "<span style='color:green'>";
  elseif ($type == "Integer")
	$type_color = "<span style='color:red'>";
  elseif ($type == "Double") {
	$type_color = "<span style='color:#0099c5'>";
	$type = "Float";
  } elseif ($type == "Boolean")
	$type_color = "<span style='color:#92008d'>";
  elseif ($type == "NULL")
	$type_color = "<span style='color:black'>";

  if (is_array($avar)) {
	$count = count($avar);
	echo "$indent" . ($var_name ? "$var_name => " : "") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
	$keys = array_keys($avar);
	foreach ($keys as $name) {
	 $value = &$avar[$name];
	 do_dump($value, "['$name']", $indent . $do_dump_indent, $reference);
	}
	echo "$indent)<br>";
  } elseif (is_object($avar)) {
	echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
	foreach ($avar as $name => $value)
	 do_dump($value, "$name", $indent . $do_dump_indent, $reference);
	echo "$indent)<br>";
  } elseif (is_int($avar))
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> $type_color" . htmlspecialchars($avar) . "</span><br>";
  elseif (is_string($avar))
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> $type_color\"" . htmlspecialchars($avar) . "\"</span><br>";
  elseif (is_float($avar))
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> $type_color" . htmlspecialchars($avar) . "</span><br>";
  elseif (is_bool($avar))
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> $type_color" . ($avar == 1 ? "TRUE" : "FALSE") . "</span><br>";
  elseif (is_null($avar))
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> {$type_color}NULL</span><br>";
  else
	echo "$indent$var_name = <span style='color:#666666'>$type(" . mb_strlen($avar, $codetype) . ")</span> " . htmlspecialchars($avar) . "<br>";

  $var = $var[$keyvar];
 }
 echo "</div>";
}

function dump() {
//  header("Content-type : text/html; charset=UTF-8");
 $funlist = func_get_args();
 $exitstring = 'exit'; //如果包含EXIT执行完后则停止
 foreach ($funlist as $key => $val) {
  if ($val == $exitstring)
	continue;
  do_dump($val, $key + 1);
  echo "<hr/>";
 }
 if (array_search($exitstring, $funlist) !== false)
  exit();
}

function nl_except_params($params, $fileds) {
 //LMS 11.21 如果没实例化FIELDS 要报错
 if (!is_array($params) || !is_array($fileds))
  return $params;
 foreach ($params as $k => $value) {
  $k1 = 'nns_' . $k;
  if (in_array($k, $fileds) || in_array($k1, $fileds))
	continue;
  unset($params[$k]);
 }

 return $params;
}

function nl_get_log_dc($config, $params = NULL) {
        $db_obj = new nl_dc($config, $params, 'log_db');

        return $db_obj;
}

function nl_get_cms_dc($config, $params = NULL,$str_platform='cms') {
    $db_obj = new nl_dc($config, $params, $str_platform);

    return $db_obj;
}

function nl_get_cms_db($db_policy,$params=NULL){
    $c = nl_get_cms_db_config($db_policy);
    if ($c===NULL) return -1;

    if (is_array($params)) {
        if (array_key_exists('db_log', $params)) {
            $c['db_log'] = $params['db_log'];  //	重构数据模块调试参数
        }
    }


    $db = np_db_factory_create($c);
    return $db;
}


function nl_get_log_db($db_policy,$params=NULL){
 $c = nl_get_log_db_config($db_policy);
 
 if ($c===NULL) return -1;

 if (is_array($params)) {
  if (array_key_exists('db_log', $params)) {
	$c['db_log'] = $params['db_log'];  //	重构数据模块调试参数
  }
 }


 $db = np_db_factory_create($c);

 return $db;
}

function nl_get_log_db_config($db_policy){
	
	if (defined('g_log_db_enable') && g_log_db_enable==1){
		$c = np_db_build_config(
				  g_log_db_host, g_log_db_username, g_log_db_password, g_log_db_name, NP_DB_TYPE_MYSQL, NP_DB_LOG_NULL
		);
	}else{
		return NULL;
	}
	
	return $c;
}

function nl_get_cms_db_config($db_policy){
    if (defined('g_cms_db_enable') && g_cms_db_enable==1){
        $c = np_db_build_config(
            g_cms_db_host, g_cms_db_username, g_cms_db_password, g_cms_db_name, NP_DB_TYPE_MYSQL, NP_DB_LOG_NULL
        );
    }else{
        return NULL;
    }

    return $c;
}



/**
 * 获取redis 对象
 * Array(
 *            'db_policy'=>db配置，标识读或写，NL_DB_WRITE | NL_DB_READ
 * $config = array(
 *      host=>'localhost',
 *      port=>''
 * )
 * @author huayi.cai
 * @date   2014-9-9
 */
function nl_get_redis($redis_policy = NL_REDIS_WRITE, $open = true)
{
	$c = nl_get_redis_config($redis_policy);
	
	if ($c === null && !class_exists("Redis"))
	{
		$redis = new np_redis_null_class($c);
	}
	else
	{
		$redis = new np_redis_class($c);

	}

	if ($open == true)
	{
		$re = $redis->open();
		//        当连接失败，切换到虚类
		if ($re === false)
		{
			unset($redis);
			$redis = new np_redis_null_class($c);
		}
	}

	return $redis;
}

function nl_get_redis_v2($redis_policy = NL_REDIS_WRITE, $platform = '')
{
	$c = nl_get_redis_config($redis_policy,$platform);

	if ($c === null && !class_exists("Redis"))
	{
		$redis = new np_redis_null_class($c);
	}
	else
	{
		$redis = new np_redis_class($c);

	}

	return $redis;
}

function nl_get_redis_config($redis_policy,$type="")
{

	$w_configs = nl_get_redis_w_config_list($type);
	$r_configs = nl_get_redis_r_config_list($type);
	$db_check = "redis_check_ini";
	if (defined("g_redis_mode"))
	{
		$redis_mode = g_redis_mode;
	}
	else
	{
		$redis_mode = 2;
	}

	//    $configs = nl_get_active_db_config_by_ini($w_configs, $r_configs);
	//
	$db_ini = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nn_cms_config';
	if ($redis_policy === NL_REDIS_WRITE)
	{
		return np_db_check::get_write_db_config($w_configs, $r_configs, $redis_mode, $db_ini, $db_check);
	}
	else
	{
		return np_db_check::get_read_db_config($w_configs, $r_configs, $redis_mode, $db_ini, $db_check);
	}
}

function nl_get_redis_w_config_list($type)
{
	$configs = array ();
	$type = empty($type)?"":"_{$type}";
	for ($i = 1; $i <= 32; $i++)
	{
		if ($i === 1 && defined("g{$type}_redis_host"))
		{
			$c = array (
					"host" => constant("g{$type}_redis_host"),
					"port" => constant("g{$type}_redis_port"),
					"passwd" => constant("g{$type}_redis_password")
			);

			if (isset($c))
			{
				array_push($configs, $c);
			}
		}
		elseif (defined("g{$type}_redis_w_host" . $i))
		{

			$c = array (
					"host" => constant("g{$type}_redis_w_host" . $i),
					"port" => constant("g{$type}_redis_w_port" . $i),
					"passwd" => constant("g{$type}_redis_w_password" . $i)
			);

			if (isset($c))
			{
				array_push($configs, $c);
			}
		}
	}

	return $configs;
}

function nl_get_redis_r_config_list($type)
{
	$configs = array ();
	$type = empty($type)?"":"_{$type}";
	for ($i = 1; $i <= 32; $i++)
	{
		if (defined("g{$type}_redis_r_host" . $i))
		{
			$c = array (
					"host" => constant("g{$type}_redis_r_host" . $i),
					"port" => constant("g{$type}_redis_r_port" . $i),
					"passwd" => constant("g{$type}_redis_r_password" . $i)
			);
			if (isset($c))
			{
				array_push($configs, $c);
			}
		}
	}

	return $configs;
}


function get_logic_result($code, $reason = "", $data = null)
{
	return array (
			"code" => $code,
			"data" => $data,
			"reason" => $reason
	);
}
